package com.coordinator.test;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * Created by Administrator on 2016/12/1.
 */

public class TempView extends Button{
    private int nDownx, nDowny;
    public TempView(Context context) {
        super(context);
    }

    public TempView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TempView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                nDownx = (int)event.getX();
                nDowny = (int)event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                int x = (int)event.getX();
                int y = (int)event.getY();

                setPosition(this, x - nDownx, y - nDowny);
                nDownx = x;
                nDowny = y;
                break;
        }
        return super.onTouchEvent(event);
    }

    private void setPosition(View v, int x, int y)
    {
        CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams)v.getLayoutParams();
        layoutParams.leftMargin = getLeft() + x;
        layoutParams.topMargin = getTop() + y;
        v.setLayoutParams(layoutParams);
    }
}
